package com.xinchao.ck_mips.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.media.AudioManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.xinchao.ck_mips.App;
import com.xinchao.ck_mips.BuildConfig;
import com.xinchao.ck_mips.R;
import com.xinchao.ck_mips.constant.CK;
import com.xinchao.ck_mips.event.LightEvent;
import com.xinchao.ck_mips.widgets.InfoDialog;

import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import de.greenrobot.event.EventBus;

/**
 * Created by wq on 2019/4/29.
 * 退出弹窗工具类
 */
public class DialogUtils {
    private static Dialog serverDialog;
    public static ServerDialogCallbackListener mServerDialogCallbackListener;

    public static ImageView imgServerClose;
    public static Button btnServerCancel;
    public static Button btnServerConfirm;
    public static EditText editMainIP;
    public static EditText editMainPort;
    public static Button btnMenuExit;

    public static InfoDialog infoDialog;
    public static TextView tvDeviceTime;
    public static TextView tvVoice;
    public static SeekBar seekBarVoice;
    public static SeekBar seekBarLight;
    public static TextView tvLight;

    public static Context mContext;

    public static void showInfoDialog(Context context) {
        try {
            View infoView = ((Activity) context).getLayoutInflater().inflate(R.layout.layout_device_info_dialog, null);
            infoDialog = new InfoDialog(context, R.style.AppDialog);

            mContext = context;

            TextView tvSoftVersion = infoView.findViewById(R.id.tvSoftVersion);
            tvSoftVersion.setText(BuildConfig.VERSION_NAME);

            TextView tvFirmWareVersion = infoView.findViewById(R.id.tvFirmwareVersion);
            tvFirmWareVersion.setText(App.iBaseMachine.getFrameworkVersion());

            TextView tvDeviceCode = infoView.findViewById(R.id.tvDeviceCode);
            if (TextUtils.isEmpty(App.iBaseMachine.getUniqueDeviceCode())) {
                tvDeviceCode.setText("暂无");
            } else {
                tvDeviceCode.setText(App.iBaseMachine.getUniqueDeviceCode());
            }

            TextView tvState = infoView.findViewById(R.id.tvState);
            tvState.setText(NetWorkUtil.isNetworkAvailable(context) ? "已连接" : "已断开");

            TextView tvNetWay = infoView.findViewById(R.id.tvNetWay);
            if (NetWorkUtil.isNetworkAvailable(context)) {
                String way = DeviceUtil.getNetworkState(context);
                try {
                    if (URLDecoder.decode(way, "utf-8").contains("SIM")) {
                        tvNetWay.setText("4G");
                    } else {
                        tvNetWay.setText(URLDecoder.decode(way, "utf-8"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                tvNetWay.setText("无");
            }

            editMainIP = infoView.findViewById(R.id.editMainIP);
            editMainPort = infoView.findViewById(R.id.editMainPort);

            TextView tvMac = infoView.findViewById(R.id.tvMac);
            tvMac.setText(App.iBaseMachine.getLocalMac());

            TextView tvIP = infoView.findViewById(R.id.tvIP);
            tvIP.setText(NetWorkUtil.isNetworkAvailable(context) ? DeviceUtil.getIP(context) : "无");

            TextView tvDensity = infoView.findViewById(R.id.tvDensity);
            tvDensity.setText(DeviceUtil.getResolution(context));

            tvVoice = infoView.findViewById(R.id.tvVoice);

            tvLight = infoView.findViewById(R.id.tvLight);
            tvLight.setText("" + ShareUtil.getInstance().getInt(CK.CK_LIGHT, 100));

            RelativeLayout lytVoice = infoView.findViewById(R.id.lytVoice);
            RelativeLayout lytLight = infoView.findViewById(R.id.lytLight);

            lytVoice.setOnKeyListener(mOnKeyVoiceListener);
            lytLight.setOnKeyListener(mOnKeyLightListener);

            Button btnSave = infoView.findViewById(R.id.btnSave);
            btnSave.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //保存逻辑

                    if (!TextUtils.isEmpty(editMainIP.getText().toString())) {
                        if (!FileUtils.checkIP(editMainIP.getText().toString())) {
                            Toast.makeText(mContext, "IP地址输入有误", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        Toast.makeText(mContext, "请输入IP地址", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (!TextUtils.isEmpty(editMainPort.getText().toString())) {
                        if (FileUtils.checkPort(editMainPort.getText().toString())) {
                            Toast.makeText(mContext, "端口输入有误", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else {
                        Toast.makeText(mContext, "请输入端口地址", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
                    ShareUtil.getInstance().put(CK.CK_IP, "http://" + editMainIP.getText().toString() + ":" + editMainPort.getText().toString() + "/");
                }
            });

            seekBarVoice = infoView.findViewById(R.id.seekBar_voice);
            seekBarVoice.setProgress(ShareUtil.getInstance().getInt(CK.SP_VOLUME, CK.DEFAULT_VOLUME));
            seekBarLight = infoView.findViewById(R.id.seekBar_light);
            seekBarLight.setProgress(ShareUtil.getInstance().getInt(CK.CK_LIGHT, 100));
            seekBarLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                    //亮度
                    DeviceUtil.setScreenBirghtness(context, seekBar.getProgress());
                    tvLight.setText("" + DeviceUtil.getScreenBrightness(context));
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });

            tvDeviceTime = infoView.findViewById(R.id.tvDeviceTime);
            tvDeviceTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));

            TextView tvWorkdayOnOffTime = infoView.findViewById(R.id.tvWorkDayOnOffTime);
            String workOnTime = ShareUtil.getInstance().getString(CK.WORK_DAY_ON_TIME, "");
            String workOffTime = ShareUtil.getInstance().getString(CK.WORK_DAY_OFF_TIME, "");
            if (!TextUtils.isEmpty(workOnTime)) {
                workOnTime = workOnTime.substring(0, workOnTime.lastIndexOf(":"));
            } else {
                workOnTime = "06:30";
            }

            if (!TextUtils.isEmpty(workOffTime)) {
                workOffTime = workOffTime.substring(0, workOffTime.lastIndexOf(":"));
            } else {
                workOffTime = "22:00";
            }

            tvWorkdayOnOffTime.setText(workOnTime + "/" + workOffTime);
            TextView tvWeekdayOnOffTime = infoView.findViewById(R.id.tvWeekdayOnOffTime);
            String weekdayOnTime = ShareUtil.getInstance().getString(CK.WEEK_DAY_ON_TIME, "");
            String weekdayOffTime = ShareUtil.getInstance().getString(CK.WEEK_DAY_OFF_TIME, "");
            if (!TextUtils.isEmpty(weekdayOnTime)) {
                weekdayOnTime = weekdayOnTime.substring(0, weekdayOnTime.lastIndexOf(":"));
            } else {
                weekdayOnTime = "06:30";
            }

            if (!TextUtils.isEmpty(weekdayOffTime)) {
                weekdayOffTime = weekdayOffTime.substring(0, weekdayOffTime.lastIndexOf(":"));
            } else {
                weekdayOffTime = "22:00";
            }

            tvVoice.setText("" + ShareUtil.getInstance().getInt(CK.SP_VOLUME, CK.DEFAULT_VOLUME));
            tvWeekdayOnOffTime.setText(weekdayOnTime + "/" + weekdayOffTime);
            infoDialog.setContentView(infoView);
            WindowManager.LayoutParams params = infoDialog.getWindow().getAttributes();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
            String[] display = DeviceUtil.getResolution(context).split("x");
            if (displayMetrics.heightPixels > displayMetrics.widthPixels) {
                //竖屏
                if (Integer.parseInt(display[0]) < 800) {
                    params.width = (int) (0.85d * displayMetrics.widthPixels);
                } else {
                    params.width = (int) (0.6d * displayMetrics.widthPixels);
                }
            } else {
                //横屏
                if (Integer.parseInt(display[0]) < 1400) {
                    params.width = (int) (0.6d * displayMetrics.widthPixels);
                } else {
                    params.width = (int) (0.35d * displayMetrics.widthPixels);
                }

            }
            params.gravity = Gravity.CENTER;
            infoDialog.getWindow().setAttributes(params);
            infoDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        /*if (infoDialog != null && infoDialog.isShowing()) {
            Message msg = Message.obtain();
            msg.what = 1;
            handler.sendMessage(msg);
        }*/
    }

    static View.OnKeyListener mOnKeyVoiceListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            try {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_DPAD_LEFT:
                        case KeyEvent.KEYCODE_DPAD_RIGHT:
                            seekBarVoice.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                                    ShareUtil.getInstance().put(CK.SP_VOLUME, i);
                                    App.iBaseMachine.setVolume(i, AudioManager.STREAM_MUSIC);
                                    DeviceUtil.setVolume(i,mContext);
                                    tvVoice.setText("" + i);
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });

                            seekBarVoice.onKeyDown(keyCode, event);

                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
            }
            return false;
        }
    };

    static View.OnKeyListener mOnKeyLightListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            try {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    switch (keyCode) {
                        case KeyEvent.KEYCODE_DPAD_LEFT:
                        case KeyEvent.KEYCODE_DPAD_RIGHT:
                            seekBarLight.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                                    ShareUtil.getInstance().put(CK.CK_LIGHT, i);
                                    tvLight.setText("" + i);
                                    EventBus.getDefault().post(new LightEvent(i));
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });

                            seekBarLight.onKeyDown(keyCode, event);
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
            }
            return false;
        }
    };

    /*static Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1 && infoDialog != null && infoDialog.isShowing()) {
                tvDeviceTime.setText(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                Message obj = Message.obtain();
                obj.what = 1;
                handler.sendMessage(obj);
            }
        }
    };*/

    public static void hideInfoDialog() {
        if (infoDialog != null && infoDialog.isShowing()) {
            infoDialog.dismiss();
            infoDialog = null;
        }
    }

    /**
     * 显示服务器弹窗
     */
    /*public static void showServerDialog(Context mContext, ServerDialogCallbackListener mListener) {
        View serverView = ((Activity) mContext).getLayoutInflater().inflate(R.layout.layout_server_dialog, null);
        btnServerCancel = serverView.findViewById(R.id.btnCancel);
        btnServerConfirm = serverView.findViewById(R.id.btnConfirm);
        imgServerClose = serverView.findViewById(R.id.imgClose);

        editMainIP = serverView.findViewById(R.id.editMainIP);
        editMainPort = serverView.findViewById(R.id.editMainPort);

        serverDialog = new Dialog(mContext, R.style.AppDialog);
        serverDialog.setContentView(serverView);
        serverDialog.setCancelable(false);

        mServerDialogCallbackListener = mListener;
        btnServerConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(editMainIP.getText().toString())) {
                    if (!FileUtils.checkIP(editMainIP.getText().toString())) {
                        Toast.makeText(mContext, "IP地址输入有误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    Toast.makeText(mContext, "请输入IP地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!TextUtils.isEmpty(editMainPort.getText().toString())) {
                    if (FileUtils.checkPort(editMainPort.getText().toString())) {
                        Toast.makeText(mContext, "端口输入有误", Toast.LENGTH_SHORT).show();
                        return;
                    }
                } else {
                    Toast.makeText(mContext, "请输入端口地址", Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, "保存成功", Toast.LENGTH_SHORT).show();
                ShareUtil.getInstance().put(CK.CK_IP, "http://" + editMainIP.getText().toString() + ":" + editMainPort.getText().toString() + "/");
                if (null != mServerDialogCallbackListener) {
                    mServerDialogCallbackListener.serverConfirm();
                }
            }
        });


        btnServerCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mServerDialogCallbackListener) {
                    mServerDialogCallbackListener.serverCancel();
                }
            }
        });

        imgServerClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mServerDialogCallbackListener) {
                    mServerDialogCallbackListener.serverClose();
                }
            }
        });

        WindowManager.LayoutParams params = serverDialog.getWindow().getAttributes();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) mContext).getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
        if (displayMetrics.heightPixels > displayMetrics.widthPixels) {
            //竖屏
            params.width = (int) (0.72d * displayMetrics.widthPixels);
            params.height = (int) (0.25 * displayMetrics.heightPixels);
        } else {
            //横屏
            params.width = (int) (0.6d * displayMetrics.widthPixels);
            params.height = (int) (0.6 * displayMetrics.heightPixels);
        }
        params.gravity = Gravity.CENTER;
        serverDialog.getWindow().setAttributes(params);
        serverDialog.show();
    }
*/
    public static void hideServerDialog() {
        if (serverDialog != null && serverDialog.isShowing()) {
            serverDialog.dismiss();
            serverDialog = null;
        }
    }

    public interface ServerDialogCallbackListener {
        void serverCancel();

        void serverConfirm();

        void serverClose();
    }

}
